/**
 * 此为组织岗位管理定开编辑表格组件，不可通用
 */
import React, { useContext, useState, useEffect, useRef } from 'react';
import { useDispatch } from 'umi';
import { Table, Input, Button, Popconfirm, Form, Select } from 'antd';

const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false} key={index}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  dataSource,
  ...restProps
}) => {
  const [editing, setEditing] = useState(!(editable && typeof record[dataIndex] !== 'undefined'));
  const [selectData, setSelectData] = useState([]);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  const dispatch = useDispatch();

  useEffect(() => {
    if (editing && inputRef.current) {
      inputRef.current.focus();
      dispatch({
        type: 'orgManageModel/getListDistinctPositionNames',
        payload: {},
      }).then((data) => {
        setSelectData(data.filter(Boolean).map((name) => ({ name })));
      });
    }
  }, [editing]);
  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;
  if (editable) {
    if (editing) {
      if (record?.key?.indexOf('exist') !== -1) {
        childNode = (
          <Form.Item
            style={{
              margin: 0,
            }}
            name={dataIndex}
            rules={[
              {
                required: true,
                message: `请选择${title}`,
              },
            ]}
          >
            <Select
              ref={inputRef}
              placeholder={`请选择${title}`}
              onChange={save}
              showSearch
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {selectData.map((d, i) => (
                <Select.Option key={i} value={d.name}>
                  {d.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        );
      } else {
        childNode = (
          <Form.Item
            style={{
              margin: 0,
            }}
            name={dataIndex}
            rules={[
              {
                required: true,
                message: `请输入${title}`,
              },
            ]}
          >
            <Input
              ref={inputRef}
              placeholder={`请输入${title}`}
              onPressEnter={save}
              onBlur={save}
            />
          </Form.Item>
        );
      }
    } else {
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        // onClick={toggleEdit}
      >
        {children}
      </div>;
    }
  }

  return <td {...restProps}>{childNode}</td>;
};

const EditableTable = (props) => {
  const { columns, dataSource, handleDataSourceChange, handleDataSave, ...rest } = props;

  const handleSave = (row) => {
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    handleDataSourceChange(newData);
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  const columnsData = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
        dataSource,
      }),
    };
  });

  return (
    <Table
      components={components}
      rowClassName={(record) => (record.isDel ? 'editable-row-del' : 'editable-row')}
      dataSource={dataSource}
      columns={columnsData}
      {...rest}
    />
  );
};

export default EditableTable;
